package com.erp.interceptor;

import com.erp.erp_entitys.User.UserEntity;
import com.erp.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.sql.Statement;
import java.util.Properties;

@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
        @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
        @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
@Slf4j
public class SqlInterceptor  implements Interceptor {

    public SqlInterceptor(DataSource dataSource) {

       System.out.println(" ");
    }

    @Override
    public Object intercept(  Invocation invocation) throws Throwable {

        Object target = invocation.getTarget();
        StatementHandler statementHandler = (StatementHandler) target;
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql(); //获取sql
        Object parameterObject = boundSql.getParameterObject();
        long start = System.currentTimeMillis();
        boolean tf=true;
        try {

            return invocation.proceed(); //sql运行
        } catch (Throwable t) {
            tf=false;
           // System.out.println(String.format("错误SQL=%s", sql));
            throw t;
        } finally {
            if(tf){
                saveOprationtor(sql,parameterObject);
            }

           // System.out.println(String.format("耗时%s ms, SQL=%s", (System.currentTimeMillis() - start), sql));
        }
    }



    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {
       System.out.println(properties);
    }
    private void saveOprationtor(String sqlstr,Object object){

        String sql=sqlstr.trim().replace("\n","").toLowerCase();
        String sqlCommandType="";
        String tableName="";
        if(sql.trim().startsWith("update") || sql.trim().startsWith("UPDATE")){
            sqlCommandType="update";
        }else if(sql.trim().startsWith("insert")||sql.trim().startsWith("INSERT")){
            sqlCommandType="insert";
        }else if(sql.trim().startsWith("delete")||sql.trim().startsWith("DELETE")){
            sqlCommandType="delete";
        }
        if(!sqlCommandType.equals("")){
            //表名
            String[] sqls=sql.split(sqlCommandType)[1].trim().split(" ");
            tableName=sqls[0];
            if(sql.trim().startsWith("update") || sql.trim().startsWith("UPDATE")){
                sqlCommandType="update(更新)";
            }else if(sql.trim().startsWith("insert")||sql.trim().startsWith("INSERT")){
                sqlCommandType="insert(新增)";
                tableName=sqls[1].trim().split(" ")[0];
            }else if(sql.trim().startsWith("delete")||sql.trim().startsWith("DELETE")){
                sqlCommandType="delete(删除)";
            }
            try {
                HttpSession session= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
                UserEntity user=(UserEntity) session.getAttribute("user");
                if(null != user){

                    FileUtils.createLogFile(tableName,object.toString(),sqlCommandType,user.getName()+"("+user.getCode()+")",sql);
                }

            }catch (Exception e){
               // e.printStackTrace();
            }
        }


    }
}
